package com.example.qa.service.application.service;

import com.example.qa.service.application.port.in.GetChatContentCase;
import com.example.qa.service.domain.ChatCompletionRequestDTO;
import com.example.qa.service.domain.ChatCompletionResponseDTO;
import com.example.qa.service.domain.Choice;
import com.example.qa.service.domain.Message;
import com.example.qa.service.domain.config.MoonShotConfig;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @program: qa-sys
 * @description:
 * @author: fks
 * @create: 2025-09-16 22:51
 **/
@Component
@Slf4j
public class GetChatContentService implements GetChatContentCase {
    @Resource
    private RestTemplate restTemplate;

    @Resource
    private RabbitTemplate rabbitTemplate;
    @Resource
    private MoonShotConfig moonShotConfig;
    @Override
    public List<Choice> getChatContent(String question) {
        log.info("demo");
        //创建请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Authorization", "Bearer " + moonShotConfig.getKey());
        //创建请求体
        ChatCompletionRequestDTO request = new ChatCompletionRequestDTO();
        request.setModel(moonShotConfig.getModel());
        request.setTemperature(0.6);
        //创建消息列表
        Message systemMessage = new Message();
        systemMessage.setRole("system");
        systemMessage.setContent("你是 Kimi，由 Moonshot AI 提供的人工智能助手，你更擅长中文和英文的对话。你会为用户提供安全，有帮助，准确的回答。同时，你会拒绝一切涉及恐怖主义，种族歧视，黄色暴力等问题的回答。Moonshot AI 为专有名词，不可翻译成其他语言。");

        Message userMessage=new Message();
        userMessage.setRole("user");
        userMessage.setContent(question);

        request.setMessages(Arrays.asList(
                systemMessage,userMessage
        ));

        //创建Http实体
        HttpEntity<ChatCompletionResponseDTO> response= restTemplate.exchange(
                moonShotConfig.getUrl(),
                HttpMethod.POST,
                new HttpEntity<>(request, headers),
                ChatCompletionResponseDTO.class
        );

        log.info("response:{}",response);

        List<Choice> choices = response.getBody().getChoices();
//        List<Message> messages = choices.stream().map(Choice::getMessage).collect(Collectors.toList());
        Message message = choices.get(0).getMessage();
        log.info("messages:{}",message);
        rabbitTemplate.convertAndSend("test", message);
        return choices;
    }
}
